package com.example.freeengine.wallpaper.fragment.cyclerefresh;

import static android.app.Activity.RESULT_OK;
import static android.content.Intent.EXTRA_ALLOW_MULTIPLE;
import static android.provider.Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION;

import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.freeengine.R;
import com.example.freeengine.databinding.FragmentAlbumPictureListBinding;
import com.example.freeengine.wallpaper.constants.WallPaperConstant;
import com.example.freeengine.wallpaper.fragment.WallPaperViewModel;
import com.example.freeengine.wallpaper.fragment.cyclerefresh.albumlist.AlbumPictureListAdapter;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbumItem;
import com.example.freeengine.wallpaper.persistence.repository.WallPaperCycleRefreshRepository;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;


/**
 * @author Terry Deng
 */
public class AlbumPictureListFragment extends Fragment {

    private static final int REQUEST_IMAGE_SELECT = 1;
    private static final String TAG = AlbumPictureListFragment.class.getSimpleName();
    WallPaperViewModel wallPaperViewModel;
    WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository;
    FragmentAlbumPictureListBinding viewBinding;
    AlbumPictureListAdapter albumPictureListAdapter;

    public AlbumPictureListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        viewBinding = FragmentAlbumPictureListBinding.inflate(inflater);
        return viewBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // requestPermissions(new String[]{Manifest.permission.MANAGE_DOCUMENTS}, 1);

        wallPaperCycleRefreshRepository = new WallPaperCycleRefreshRepository(requireContext());
        wallPaperViewModel = new ViewModelProvider(requireActivity()).get(WallPaperViewModel.class);
        albumPictureListAdapter = new AlbumPictureListAdapter(requireContext(), wallPaperViewModel, wallPaperCycleRefreshRepository);

        viewBinding.recyclerViewAlbumPictureList.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.recyclerViewAlbumPictureList.setAdapter(albumPictureListAdapter);
        assert getArguments() != null;
        Long albumId = getArguments().getLong("albumId");
        wallPaperViewModel.getAlbumItemList(wallPaperCycleRefreshRepository, albumId).observe(requireActivity(), new Observer<List<WallPaperCycleRefreshAlbumItem>>() {
            @Override
            public void onChanged(List<WallPaperCycleRefreshAlbumItem> wallPaperCycleRefreshAlbumItems) {
                Log.i(TAG, "onChanged: ");
                albumPictureListAdapter.submitList(wallPaperCycleRefreshAlbumItems);
            }
        });

        viewBinding.btnWallpaperCyclerefreshAlbumPictureAdd.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");//选择图片
            //intent.setType(“audio/*”); //选择音频
            //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
            //intent.setType(“video/*;image/*”);//同时选择视频和图片
            //intent.setType("*/*");//无类型限制
            intent.putExtra(EXTRA_ALLOW_MULTIPLE, true);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_IMAGE_SELECT);
        });



    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_SELECT && resultCode == RESULT_OK && data != null){
            List<Uri> imagesUri = new ArrayList<>();
            if (data.getClipData() != null) {
                for (int i = 0; i < data.getClipData().getItemCount(); i++) {
                    Log.i(TAG, "onActivityResult: " + data.getClipData().getItemAt(i).getUri());
                    imagesUri.add(data.getClipData().getItemAt(i).getUri());
                }
            }else if (data.getData() != null){
                Log.i(TAG, "onActivityResult: " + data.getData());
                imagesUri.add(data.getData());
                try (InputStream inputStream = getContext().getContentResolver().openInputStream(data.getData())){
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (!imagesUri.isEmpty()){
                assert getArguments() != null;
                Long albumId = getArguments().getLong("albumId");

                // 复制文件
                File dstDir = new File(requireContext().getFilesDir() + WallPaperConstant.WALLPAPER_CYCLEREFRESH_ALBUM_FILE_PATH);
                if (!dstDir.exists()) dstDir.mkdirs();
                List<String> fileNames = new ArrayList<>();
                for (Uri uri : imagesUri){
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + "_" + imagesUri.indexOf(uri) + ".jpeg";
                    File dstFile = new File(dstDir, imageFileName);
                    if (!dstFile.exists()) {
                        try {
                            dstFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    byte[] fData = new byte[1024];
                    int len = 0;
                    try (InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
                            OutputStream os = new FileOutputStream(dstFile);){
                        while ((len = inputStream.read(fData)) > 0){
                            os.write(fData, 0, len);
                        }
                        fileNames.add(dstFile.getAbsolutePath());
                    } catch (IOException e) {
                        e.printStackTrace();
                        if (dstFile != null) dstFile.delete();
                    }
                }
                try {
                    wallPaperCycleRefreshRepository.insertAlbumItem(wallPaperViewModel.createWallPaperCycleRefreshAlbumItems(fileNames, albumId));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}